<script lang="ts">
	import type { Snippet } from 'svelte';
	import { onMount, onDestroy, tick } from 'svelte';
	interface Props {
		scrollWidth?: number;
		scrollPadding?: number; //防止浏览器倍数,最小1px
		innerPadding?: string;
		height?: number | string;
		scrollContainerRef?: HTMLElement | null;
		scrollTypeX?: 'scroll' | 'auto' | 'hidden';
		scrollTypeY?: 'scroll' | 'auto' | 'hidden';		
		onScroll?: (event: Event) => void;
		onScrollPositionChange?: (position: { scrollTop: number; scrollLeft: number }) => void;
		onScrollbarChange?: (
			hasVerticalScroll: boolean,
			scrollbarWidth: number,
			hasHorizontalScroll: boolean,
			scrollbarHeight: number
		) => void;
		checkScrollbar?: (() => void | Promise<void>) | undefined;
		children?: Snippet;
		[key: string]: any; // 允许剩余属性
	}
	let {
		scrollWidth = 6,
		scrollPadding = 2,
		innerPadding = '',
		height = '100%',
		scrollContainerRef = $bindable(null), // 允许双向绑定
		scrollTypeX = 'scroll',
		scrollTypeY = 'scroll',
		onScroll = () => {},
		onScrollPositionChange = () => {},
		onScrollbarChange,
		checkScrollbar = $bindable(),
		children,
		...restProps // 获取剩余 props 用于透传到根元素
	}: Props = $props();

	// 新增状态：控制滚动条是否显示
	let showScrollbar = $state(false);

	function handleScroll(event: Event) {
		// 调用滚动事件回调
		onScroll(event);

		// 调用滚动位置变化回调
		if (scrollContainerRef) {
			const scrollTop = scrollContainerRef.scrollTop;
			const scrollLeft = scrollContainerRef.scrollLeft;
			onScrollPositionChange({ scrollTop, scrollLeft });
		}
	}

	// 鼠标移入容器时显示
	function handleMouseEnter() {
		showScrollbar = true;
	}

	// 鼠标移出容器时隐藏（延迟300ms，避免频繁切换）
	function handleMouseLeave() {
		showScrollbar = false;
	}

	let hasVerticalScroll = $state(false);
	let hasHorizontalScroll = $state(false);

	// 检测滚动条的核心逻辑
	const triggerCheck = () => {
		if (!scrollContainerRef) return;
		// console.log('执行次数----------');

		// 允许 1px 的误差
		const hasVert = scrollContainerRef.scrollHeight > scrollContainerRef.clientHeight;
		const hasHoriz = scrollContainerRef.scrollWidth > scrollContainerRef.clientWidth;

		if (hasVert !== hasVerticalScroll || hasHoriz !== hasHorizontalScroll) {
			// console.log('滚动条状态变更1:', hasVert, hasHorizontalScroll);
			hasVerticalScroll = hasVert;
			hasHorizontalScroll = hasHoriz;
			// 等待 DOM 更新
			// await tick();
			const vWidth = hasVert ? scrollContainerRef.offsetWidth - scrollContainerRef.clientWidth : 0;

			const hHeight = hasHoriz
				? scrollContainerRef.offsetHeight - scrollContainerRef.clientHeight
				: 0;

			onScrollbarChange?.(hasVert, vWidth, hasHoriz, hHeight);
		}
	};
	checkScrollbar = triggerCheck;
	const handleResize = () => {
		requestAnimationFrame(triggerCheck);
	};
	let observer: ResizeObserver;
	onMount(() => {
		if (scrollContainerRef) {
			// 初始化高度

			observer = new ResizeObserver(handleResize);
			observer.observe(scrollContainerRef);
		}
	});

	onDestroy(() => {
		observer?.disconnect();
	});
</script>

<div
	class="scroll"
	role="region"
	style="--scroll-width: {scrollWidth}px; --scroll-padding:{scrollPadding}px;"
	style:height={height ?? '100%'}
	style:--scroll-type-x={scrollTypeX}
	style:--scroll-type-y={scrollTypeY}
	onmouseenter={handleMouseEnter}
	onmouseleave={handleMouseLeave}
	{...restProps}
>
	<div
		class="scroll-container"
		bind:this={scrollContainerRef}
		onscroll={handleScroll}
		class:show-scrollbar={showScrollbar || scrollTypeX === 'auto' || scrollTypeY === 'auto'}
		style:padding={innerPadding}
		style:contain="content"
	>
		{@render children?.()}
	</div>
</div>

<style scoped lang="scss">
	.scroll {
		position: relative;
		width: 100%;
		padding: calc(var(--scroll-width) + var(--scroll-padding)) var(--scroll-padding)
			var(--scroll-padding) calc(var(--scroll-width) + var(--scroll-padding));
		box-sizing: border-box;
		overflow: hidden; /* 防止外部溢出 */

		.scroll-container {
			position: relative;
			width: 100%;
			height: 100%; //防止浏览器倍数，造成闪烁
			overflow-x: var(--scroll-type-x, scroll);
			overflow-y: var(--scroll-type-y, scroll);
			box-sizing: border-box;
			// 直接在这里控制滚动条显示
			&.show-scrollbar::-webkit-scrollbar-thumb {
				background-color: var(--color-info-400);
			}

			&.show-scrollbar::-webkit-scrollbar-thumb:hover {
				background-color: var(--color-info-500);
			}
		}

		.scroll-container::-webkit-scrollbar {
			width: var(--scroll-width);
			height: var(--scroll-width);
		}

		.scroll-container::-webkit-scrollbar-track {
			background-color: transparent;
		}

		.scroll-container::-webkit-scrollbar-thumb {
			background-color: transparent;
			border-radius: calc(var(--scroll-width) / 2);
			transition: background-color 0.2s ease;
		}

		.scroll-container::-webkit-scrollbar-corner {
			background-color: transparent;
		}
	}
</style>
